package io.renren.modules.yckj.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.yckj.dto.CouponsDTO;
import io.renren.modules.yckj.dto.CouponsLogsDTO;
import io.renren.modules.yckj.dto.UserDTO;
import io.renren.modules.yckj.excel.CouponsLogsExcel;
import io.renren.modules.yckj.service.CouponsLogsService;
import io.renren.modules.yckj.service.CouponsService;
import io.renren.modules.yckj.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 优惠券日志
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2025-04-16
 */
@RestController
@RequestMapping("yckj/couponslogs")
@Tag(name = "优惠券日志")
public class CouponsLogsController {
    @Autowired
    private CouponsLogsService couponsLogsService;
    @Autowired
    private CouponsService couponsService;
    @Autowired
    private UserService userService;

    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String")

    })
    @RequiresPermissions("yckj:coupons:page")
    public Result<PageData<CouponsLogsDTO>> page(@RequestParam Map<String, Object> params) {
        PageData<CouponsLogsDTO> page = couponsLogsService.page(params);

        return new Result<PageData<CouponsLogsDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    @RequiresPermissions("yckj:coupons:page")
    public Result<CouponsLogsDTO> get(@PathVariable("id") Long id) {
        CouponsLogsDTO data = couponsLogsService.get(id);

        return new Result<CouponsLogsDTO>().ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
    @LogOperation("保存")
    @RequiresPermissions("yckj:coupons:page")
    public Result save(@RequestBody CouponsLogsDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        CouponsDTO couponsDTO = couponsService.get(dto.getCouponsId());
        if (couponsDTO != null && couponsDTO.getDeadlineTime().getTime() > new Date().getTime()) {
            if (!dto.getUserIdNameList().isEmpty()
                    && (couponsDTO.getNum() - couponsDTO.getReceived() >= dto.getUserIdNameList().size())) {
                CouponsLogsDTO saveDto = ConvertUtils.sourceToTarget(couponsDTO, CouponsLogsDTO.class);
                saveDto.setCouponsId(dto.getCouponsId());
                dto.getUserIdNameList().forEach(userIdName -> {
                    Long userId = Long.valueOf(userIdName.split(",")[0]);
                    String username = userIdName.split(",")[1];
                    saveDto.setId(null);
                    saveDto.setUserId(userId);
                    saveDto.setUsername(username);
                    saveDto.setCreateTime(new Date());
                    saveDto.setUpdateTime(new Date());
                    couponsLogsService.save(saveDto);
                    couponsDTO.setReceived(couponsDTO.getReceived() + 1);
                    couponsService.update(couponsDTO);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });
            } else {
                return new Result().error(1, "分发数量超出优惠券数量！");
            }
        } else {
            return new Result().error(1, "当前优惠券不存在或已过期！");
        }
        return new Result();
    }

    @PutMapping
    @Operation(summary = "修改")
    @LogOperation("修改")
    @RequiresPermissions("yckj:coupons:page")
    public Result update(@RequestBody CouponsLogsDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        couponsLogsService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @Operation(summary = "删除")
    @LogOperation("删除")
    @RequiresPermissions("yckj:couponslogs:delete")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        couponsLogsService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @Operation(summary = "导出")
    @LogOperation("导出")
    @RequiresPermissions("yckj:coupons:page")
    public void export(@RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<CouponsLogsDTO> list = couponsLogsService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "优惠券日志", list, CouponsLogsExcel.class);
    }

    @GetMapping("user/list")
    @Operation(summary = "列表,couponsId优惠券id")
//    @RequiresPermissions("yckj:user:page")
    public Result<List<UserDTO>> userList(@RequestParam Map<String, Object> params) {

        List<UserDTO> userDTOS = userService.list(params);
        List<CouponsLogsDTO> list = couponsLogsService.list(params);
        userDTOS.forEach(userDTO -> {
            userDTO.setDisabled(false);
            list.forEach(couponsLogsDTO -> {
                if (userDTO.getId().equals(couponsLogsDTO.getUserId())) {
                    userDTO.setDisabled(true);
                }
            });
        });
        return new Result<List<UserDTO>>().ok(userDTOS);
    }
}